# Copyright (c) 2024, lanlian and contributors
# For license information, please see license.txt

import json

import frappe
from frappe import _, msgprint
from frappe.model.mapper import get_mapped_doc
from frappe.utils import cint, cstr, flt
from frappe.model.document import Document


class EMSExternalMaintenance(Document):
	# 保存前自动计算预计完成时长
	def before_save(self):
		h1 = frappe.utils.time_diff_in_hours(self.expected_finish_date, self.happen_date) #根据日期计算小时差
		h2 = frappe.utils.time_diff_in_hours(self.expected_finish_time, self.ems_happen_time) #根据时间计算小时差
		self.finish_hours = h1 + h2


	def before_insert(self):
		# B路线校验:一个外部维修单不能有2个非取消状态外部维修单
		if self.ems_fault_report and frappe.db.exists({"doctype": self.doctype, "ems_fault_report": self.ems_fault_report, "docstatus": ["in", (0,1)] }):
			frappe.throw(_("EMS External Maintenance Is Created. The BillNo is:{0}").format(frappe.db.exists({"doctype": self.doctype, "ems_fault_report": self.ems_fault_report, "docstatus": ["in", (0,1)] })))
		# 是否与A路线冲突校验: 如果故障报修单已经被有效派工单关联了, 就提示冲突
		if frappe.db.exists({"doctype": "EMS Fault Repair Task", "ems_fault_report": self.ems_fault_report, "docstatus": ["in", (0,1)] }):
			frappe.throw(("该源单'故障报修单'已经下推了'故障派工单': {0}, 不允许再下推'外部维修单'. 建议取消'故障派工单'或新增'故障报修单' ").format(frappe.db.exists({"doctype": "EMS Fault Repair Task", "ems_fault_report": self.ems_fault_report, "docstatus": ["in", (0,1)] })))

# 外部维修单下推验收结算单
@frappe.whitelist()
def make_acceptance_settlement(source_name, target_doc=None, args=None):
	doc = get_mapped_doc(
		"EMS External Maintenance",
		source_name,
		{
			"EMS External Maintenance": {
				"doctype": "EMS Acceptance Settlement",
				"field_map": {"amount_include_tax": "other_cost", "name": "ems_external_maintenance"},
				"validation": {"docstatus": ["=", 1],},
			},
		},
		target_doc,
		ignore_permissions=True,
	)

	return doc
